/**
 * Vue Router
 *
 * @library
 *
 * https://router.vuejs.org/en/
 */

// Lib imports
import Vue from 'vue'
import VueAnalytics from 'vue-analytics'
import Router from 'vue-router'
import Meta from 'vue-meta'

// Routes
import paths from './paths'
import auth from '@/utils/token'

function route(path, view, meta, children) {
	let to = {
		name: view,
		path: path ,
		meta: meta,
		component: (resovle) =>
			import(
				`@/views/${view}.vue`
			).then(resovle),
		children: !children ? children : children.map(child => route(child.path, child.view, children.meta, child.children))
	}
	return to;
}

Vue.use(Router)

// Create a new router
const router = new Router({
	mode: 'history',
	routes: paths.map(path => route(path.path, path.view, path.meta, path.children)).concat([{
		path: '*',
		redirect: '/login'
	}]),
	scrollBehavior(to, from, savedPosition) {
		if(savedPosition) {
			return savedPosition
		}
		if(to.hash) {
			return {
				selector: to.hash
			}
		}
		return {
			x: 0,
			y: 0
		}
	}
})


router.beforeEach((to, from, next) => {
	if(to.meta.requireAuth) { // 判断该路由是否需要登录权限
		if(auth.isAuth()) {
			next();
		} else {
			next({
				path: '/login'
			});
		}
	} else {
		next();
	}

})

Vue.use(Meta)

// Bootstrap Analytics
// Set in .env
// https://github.com/MatteoGabriele/vue-analytics
if(process.env.GOOGLE_ANALYTICS) {
	Vue.use(VueAnalytics, {
		id: process.env.GOOGLE_ANALYTICS,
		router,
		autoTracking: {
			page: process.env.NODE_ENV !== 'development'
		}
	})
}

export default router
